package com.ailiwu.www.ailiwu.Fragment;

import android.content.Intent;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.ailiwu.www.ailiwu.R;
import com.ailiwu.www.ailiwu.activity.CollectionRecylerActivity;
import com.ailiwu.www.ailiwu.activity.PostRecylerActivity;
import com.ailiwu.www.ailiwu.activity.PurchaseActivity;
import com.ailiwu.www.ailiwu.adapter.MyRecyclerViewAdapter;
import com.ailiwu.www.ailiwu.base.BaseFragment;
import com.ailiwu.www.ailiwu.base.MyApplication;
import com.ailiwu.www.ailiwu.bean.GameAdInfo;
import com.ailiwu.www.ailiwu.bean.HomeADBean;
import com.ailiwu.www.ailiwu.bean.HomeHotF4Icon;
import com.ailiwu.www.ailiwu.bean.ItemBean;
import com.ailiwu.www.ailiwu.url.Urls;
import com.ailiwu.www.ailiwu.utils.Logger;
import com.ailiwu.www.ailiwu.views.ImageTextButton;
import com.ailiwu.www.ailiwu.views.ScrollAdView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.ArrayList;
import java.util.List;

import kale.ui.view.rcv.ExRcvAdapterWrapper;


/**
 * Author:    XiYoung
 * Version    V1.0
 * Date:      2015/12/3 000316:58
 * Description:
 * Modification  History:
 * Date         	Author        		Version        	Description
 * -----------------------------------------------------------------------------------
 * 2015/12/3 0003       XiYoung              1.0                   1.0
 * Why & What is modified:
 */
public class HomeFristFragment extends BaseFragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private ImageTextButton imageTextButton1;
    private ImageTextButton imageTextButton2;
    private ImageTextButton imageTextButton3;
    private ImageTextButton imageTextButton4;
    private RecyclerView mRecyclerView;
    private ArrayList<ItemBean.DataEntity.ItemsEntity> itemsEntities = new ArrayList<>();
    private MyRecyclerViewAdapter myRecyclerViewAdapter;
    ArrayList<GameAdInfo> AdBeanList = new ArrayList<>();
    private ScrollAdView mScrollAdView;
    private List<HomeADBean.DataEntity.BannersEntity> banners;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private boolean isReflash;
    private String next_url;

    @Override
    protected View inflateView() {

        return View.inflate(getActivity(), R.layout.fragement_home_first, null);
    }

    @Override
    protected void initView(View view) {
        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.mainColor);
        mSwipeRefreshLayout.setOnRefreshListener(this);

        /**设置recyclerView*/
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView_home_first);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                int itemCount = layoutManager.getItemCount();
                if (lastVisibleItemPosition + 1 == itemCount) {
                    //加载下一页内容
                    if (!isReflash) {
                        updataRecycler(next_url);
                    }
                }
            }
        });
        myRecyclerViewAdapter = new MyRecyclerViewAdapter(mAcAvtivity, itemsEntities);
        View mHeaderView = LayoutInflater.from(getContext()).inflate(R.layout.layout_adbanner, null);

        ExRcvAdapterWrapper adapterWrapper = new ExRcvAdapterWrapper<>(myRecyclerViewAdapter, layoutManager);
        adapterWrapper.setHeaderView(mHeaderView);
        mRecyclerView.setAdapter(adapterWrapper);
        //设置广告滚动
        mScrollAdView = (ScrollAdView) mHeaderView.findViewById(R.id.adView);
        initAdData();

        //设置四个图标
        imageTextButton1 = (ImageTextButton) mHeaderView.findViewById(R.id.image_text_button1);
        mScrollAdView.setLayoutParams(new LinearLayout.LayoutParams(MyApplication.mDisplayWitdh, MyApplication.mDisplayHeight / 4));

        imageTextButton1.setOnClickListener(this);
        imageTextButton2 = (ImageTextButton) mHeaderView.findViewById(R.id.image_text_button2);
        imageTextButton2.setOnClickListener(this);
        imageTextButton3 = (ImageTextButton) mHeaderView.findViewById(R.id.image_text_button3);
        imageTextButton3.setOnClickListener(this);
        imageTextButton4 = (ImageTextButton) mHeaderView.findViewById(R.id.image_text_button4);
        imageTextButton4.setOnClickListener(this);

    }

    private void initAdData() {
        httpUtils.send(HttpRequest.HttpMethod.GET, Urls.URL_HOME_BANNER, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                if (result != null) {
                    HomeADBean homeADBean = gson.fromJson(result, HomeADBean.class);
                    banners = homeADBean.data.banners;
                    AdBeanList.clear();
                    for (int i = 0; i < banners.size(); i++) {
                        String cover_image_url = banners.get(i).image_url;
                        ;
                        AdBeanList.add(new GameAdInfo("", "", cover_image_url));
                    }
                    mScrollAdView.SetAdsBeanList(AdBeanList);
                    //设置滚动广告页面监听
                    mScrollAdView.setOnPageImageClickListener(new ScrollAdView.OnPageImageClickListener() {
                        @Override
                        public void OnPagerClick(int position, View view) {
                            String type = banners.get(position).type;
                            if ("collection".equals(type)) {
                                String urlID = Urls.PostsID(banners.get(position).target.id);
                                Intent intent = new Intent(mAcAvtivity, PostRecylerActivity.class);
                                intent.putExtra("urlID", urlID);
                                intent.putExtra("title", banners.get(position).type);
                                mAcAvtivity.startActivity(intent);
                            } else if ("url".equals(type)) {
                                Intent intent = new Intent(mAcAvtivity, PurchaseActivity.class);
                                intent.putExtra("PURCHASE_URL", banners.get(position).target_url);
                                startActivity(intent);
                            }
                        }
                    });
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    @Override
    protected void initData() {

        updataF4Icon();
        updataRecycler(Urls.URL_HOME_RECYCLERVIEW);
    }

    private void updataRecycler(String url) {
        if (url != null) {
            isReflash = true;
            httpUtils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    String result = responseInfo.result;
                    //TODO 存入数据库
                    if (result != null) {
                        ItemBean itemBean = gson.fromJson(result, ItemBean.class);
                        List<ItemBean.DataEntity.ItemsEntity> items = itemBean.getData().getItems();
                        itemsEntities.addAll(items);
                        myRecyclerViewAdapter.notifyDataSetChanged();
                        next_url = itemBean.getData().getPaging().getNext_url();
                        isReflash = false;
                    }
                }

                @Override
                public void onFailure(HttpException e, String s) {
                    // TODO: 2015/12/3 0003 网络连接失败
                    Snackbar.make(imageTextButton1, "哎呀！网络连接失败了！！", Snackbar.LENGTH_LONG).show();
                }
            });
        }
    }

    private void updataF4Icon() {
        httpUtils.send(HttpRequest.HttpMethod.GET, Urls.URL_HOME_F4_ICON, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                Logger.i(result);
                //TODO 存入数据库
                parseF4FromJson(result);
            }


            @Override
            public void onFailure(HttpException e, String s) {
                // TODO: 2015/12/3 0003 网络连接失败
                Snackbar.make(imageTextButton1, "哎呀！网络连接失败了！！", Snackbar.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 设置F4的图片属性
     */
    protected void setF4Icon(ImageTextButton imageTextButton, String color, String imageUrl, String title) {
        imageTextButton.setTextColor(color);
        imageTextButton.setText(title);
        imageTextButton.setImageBitmapFromUrl(imageUrl);
    }

    /**
     * 解析Json并且设置F4图片、文字、颜色
     */
    protected void parseF4FromJson(String result) {
        if (result != null) {
            HomeHotF4Icon homeHotF4Icon = gson.fromJson(result, HomeHotF4Icon.class);
            List<HomeHotF4Icon.DataEntity.PromotionsEntity> promotions = homeHotF4Icon.getData().getPromotions();
            for (int i = 0; i < promotions.size(); i++) {
                String color = promotions.get(i).getColor();
                String imageUrl = promotions.get(i).getIcon_url();
                String title = promotions.get(i).getTitle();
                switch (i) {
                    case 0:
                        setF4Icon(imageTextButton1, color, imageUrl, title);
                        break;
                    case 1:
                        setF4Icon(imageTextButton2, color, imageUrl, title);
                        break;
                    case 2:
                        setF4Icon(imageTextButton3, color, imageUrl, title);
                        break;
                    case 3:
                        setF4Icon(imageTextButton4, color, imageUrl, title);
                        break;
                    default:
                        break;
                }

            }

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_text_button1:
                String urlID = Urls.PostsID(22);
                Intent intent1 = new Intent(mAcAvtivity, PostRecylerActivity.class);
                intent1.putExtra("urlID", urlID);
                intent1.putExtra("title", "美好小物");//接口不能抓取
                mAcAvtivity.startActivity(intent1);
                break;
            case R.id.image_text_button2:
                Logger.i("click");
                //全部主题
                Intent intent = new Intent(getActivity(), CollectionRecylerActivity.class);
                mAcAvtivity.startActivity(intent);
                break;
            case R.id.image_text_button3:
                Snackbar.make(imageTextButton3,"请先登录",Snackbar.LENGTH_SHORT).show();
                break;
            case R.id.image_text_button4:
                Snackbar.make(imageTextButton3,"请先登录",Snackbar.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                if (mSwipeRefreshLayout.isRefreshing()) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        }, 2000);
    }
}
